import React from 'react';
import { useRequest } from '@/hooks';
import { TreeSelectGroup } from '@/components';
import { Checkbox, message } from 'antd';
import { fetchManageList } from '@/pages/Setting/Privilege/services';
import Icons from '@/molecules/IconSelector/Icon';
import { parseRoleDataToTree } from './utils';

/**
 * 授权模板分组下拉框
 * data 数据支持外部传入, 也支持组件自动获取
 * 并对请求的数据做转换, 服务端返回的是个对象, 要转成树数组
 */
export default React.forwardRef((props, ref) => {
    const { autoFetchData = false, data, ...otherProps } = props;
    const { data: roleData, loading } = useRequest(() => fetchManageList(), {
        formatResult: res => {
            if (res) {
                if (res.code === 10000 && res.data) {
                    return parseRoleDataToTree(res.data);
                }
                message.error(res.msg);
            }
            return undefined;
        },
        ready: autoFetchData
    });

    return (
        <TreeSelectGroup
            ref={ref}
            {...otherProps}
            treeNodeFilterProp="label"
            loading={loading}
            data={(!autoFetchData ? parseRoleDataToTree(data) : roleData) || []}
            renderCheckboxOption={item => (
                <Checkbox key={item.id} value={item.id} disabled={item.disabled}>
                    {item.icon && (
                        <Icons
                            style={{
                                display: 'inline-block',
                                width: '20px',
                                height: '20px',
                                lineHeight: '20px',
                                fontSize: '12px',
                                textAlign: 'center',
                                marginRight: '4px'
                            }}
                            iconfontClassName="iconfont"
                            icon={item.icon}
                        />
                    )}
                    {item.title}
                </Checkbox>
            )}
            renderTreeOptionTitle={item => (
                <>
                    {item.icon && (
                        <Icons
                            style={{
                                display: 'inline-block',
                                width: '20px',
                                height: '20px',
                                lineHeight: '20px',
                                fontSize: '12px',
                                textAlign: 'center',
                                marginRight: '4px'
                            }}
                            iconfontClassName="iconfont"
                            icon={item.icon}
                        />
                    )}
                    {item.title}
                </>
            )}
            style={{ minWidth: '200px', ...otherProps.style }}
        />
    );
});
